package controllers

import (
	"Bok/models"
	"Bok/services"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
)

type BlogController struct {
	blogService services.BlogService
}

func NewBlogController(blogService services.BlogService) *BlogController {
	return &BlogController{
		blogService: blogService,
	}
}

// 获取分类列表
func (blogController *BlogController) GetBlogTypeList(ctx *gin.Context) {
	data, err := blogController.blogService.GetBlogTypeService()
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    401,
			"message": "controller：获取失败",
			"data":    nil,
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    data,
	})

}

// 创建分类
func (blogController *BlogController) CreateBlogType(ctx *gin.Context) {
	var blogType models.BlogTypeRequest
	if err := ctx.ShouldBind(&blogType); err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "controller：参数解析失败",
			"data":    nil,
		})
		return
	}
	fmt.Println("controller:blogType:", blogType.Name)
	err := blogController.blogService.CreateBlogTypeService(&blogType)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    401,
			"message": "controller：创建失败",
			"data":    nil,
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "创建成功",
		"data":    nil,
	})
}

// 更改分类
func (blogController *BlogController) EditBlogType(ctx *gin.Context) {
	var id uint
	id64, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		fmt.Println("controller：转换还失败了")
	}
	id = uint(id64)
	var blogType models.BlogTypeRequest
	if err := ctx.ShouldBind(&blogType); err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "controller：参数解析失败",
			"data":    nil,
		})
		return
	}

	if err := blogController.blogService.EditBlogTypeService(id, &blogType); err != nil {
		ctx.JSON(200, gin.H{
			"code":    401,
			"message": "controller：更新失败",
			"data":    nil,
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "更新成功",
		"data":    nil,
	})
}

// 删除分类
func (blogController *BlogController) DeleteBlogType(ctx *gin.Context) {
	// 批量删除
	var ids []uint
	if err := ctx.ShouldBind(&ids); err != nil {
	}

	//var id uint
	//id64, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	//if err != nil {
	//	fmt.Println("controller：转换还失败了")
	//}
	//id = uint(id64)

	if err := blogController.blogService.DeleteBlogTypeService(ids); err != nil {
		ctx.JSON(200, gin.H{
			"code":    401,
			"message": "controller：删除失败",
			"data":    nil,
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "删除成功",
		"data":    nil,
	})
}
